<?php

namespace app\common\model;

use app\common\model\BaseModel;


class Order extends BaseModel
{

    

    

    // 表名
    protected $name = 'order';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'begin_time_text',
        'medicine_type_text',
        'express_time_text',
        'create_time_text',
        'accept_time_text',
        'start_time_text',
        'end_time_text',
        'add_time_text',
        'self_care_ability_text',
        'finish_time_text',
        'complete_time_text',
        'pay_time_text',
        'refund_status_text',
        'refund_time_text',
        'status_text',
        'images_arr',
        'express_img_arr',
        'time_to_cancel',
        'leave_time_text',
        'pay_time_left'
    ];


    public static function onAfterUpdate($data)
    {
        if ($data['status']==7) {
            if($data['pay_time']&&!$data['complete_time']){
                if($data['inviter_money']>0){
                    User::money($data['inviter_money'],$data['inviter_id'],'订单完成，推荐人分成',$data['user_id']);
                }

                if($data['worker_money']>0){
                    User::money($data['worker_money'],$data['worker_id'],'订单完成,陪诊员收益');
                }

                if($data['agent_money']>0){
                    User::money($data['agent_money'],$data['agent_id'],'订单完成，城市代理人收益');
                }


                $data['complete_time']=time();
                $data->save();
            }
        }
    }


    public function getmedicineTypeList()
    {
        return ['otc' => '非处方药', 'pd' => '处方药'];
    }

    public function getSelfCareAbilityList()
    {
        return ['0' => __('Self_care_ability 0'), '1' => __('Self_care_ability 1'), '2' => __('Self_care_ability 2'), '3' => __('Self_care_ability 3')];
    }

    public function getRefundStatusList()
    {
        return ['0' => __('Refund_status 0'), '1' => __('Refund_status 1'), '2' => __('Refund_status 2')];
    }

    public function getStatusList()
    {
        return [
            '1'=>'已下单','2'=>'已支付','3'=>'已匹配（待接单）','4'=>'已接单','5'=>'服务中','6'=>'服务完成','7'=>'已完成',
            '10'=>'已取消','11'=>'支付超时自动取消','15'=>'转单申请中',
            '41'=>'退款审核中','42'=>'退款成功','43'=>'退款拒绝'
        ];
    }


    public function getStatusTextAttr($value, $data)
    {
        if(!isset($data['status']))
            return '';

        switch ($data['status']){
            case 1:
                $text='待支付';
                break;
            case 2:
                $text='已支付';
                break;
            case 3:
                $text='待接单';
                break;
            case 4:
                $text='已接单';
                break;
            case 5:
                $text='服务中';
                break;
            case 6:
                if($data['patient_commented']==1)
                    $text='用户已评';
                else
                    $text='服务完成';
                break;
            case 7:
                $text='已完成';
                break;
            case 10:
                $text='已取消';;
                break;
            case 11:
                $text='支付超时自动取消';;
                break;
            case 15:
                $text='陪诊员取消订单处理中';
                break;
            case 41:
                $text='退款审核中';
                break;
            case 42:
                $text='退款成功';
                break;
            case 43:
                $text='退款拒绝';
                break;
            default:
                $text='未知订单状态';
        }

        return $text;
    }


    public function getBeginTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['begin_time']) ? $data['begin_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getmedicineTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['medicine_type']) ? $data['medicine_type'] : '');
        $list = $this->getmedicineTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getExpressTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['express_time']) ? $data['express_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['create_time']) ? $data['create_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getAcceptTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['accept_time']) ? $data['accept_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStartTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['start_time']) ? $data['start_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['end_time']) ? $data['end_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getAddTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['add_time']) ? $data['add_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getSelfCareAbilityTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['self_care_ability']) ? $data['self_care_ability'] : '');
        $list = $this->getSelfCareAbilityList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getFinishTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['finish_time']) ? $data['finish_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCompleteTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['complete_time']) ? $data['complete_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPayTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['pay_time']) ? $data['pay_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getRefundStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['refund_status']) ? $data['refund_status'] : '');
        $list = $this->getRefundStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    public function getRefundTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['refund_time']) ? $data['refund_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getImagesArrAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['images']) ? $data['images'] : '');
        return $value ? explode(",", $value) : $value;
    }


    public function getExpressImgArrAttr($value, $data)
    {
        $value = isset($data['express_img']) ? $data['express_img'] : '';
        return $value ? explode(",", $value) : $value;
    }


    public function getTimeToCancelAttr($value, $data)
    {
        if($data['status']!=1)
            return 0;

        $time=$data['create_time']+2400-time();
        if($time<0)
            $time=0;
        return $time;
    }


    public function getLeaveTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['leave_time']) ? $data['leave_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getPayTimeLeftAttr($value, $data)
    {
        if($data['status']==1){
            $limit=config('site.pay_time_limit')?:0;
            if($limit>0){
                $last=$data['create_time']+$limit*60-time();
                if($last>0){
                    return $last;
                }
            }
        }
        return 0;
    }


    protected function setBookTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setExpressTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setAcceptTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setStartTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setEndTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setAddTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setFinishTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCompleteTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setPayTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setRefundTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id')->joinType('LEFT');
    }

    public function worker()
    {
        return $this->belongsTo('User', 'worker_id', 'id')->joinType('LEFT');
    }

    public function hospital()
    {
        return $this->belongsTo('Hospital', 'hospital_id', 'id')->joinType('LEFT');
    }


    public function patient()
    {
        return $this->belongsTo('Patient', 'patient_id', 'id')->joinType('LEFT');
    }


    public function servicebasic()
    {
        return $this->belongsTo('ServiceBasic', 'service_basic_id', 'id')->joinType('LEFT');
    }


    public function hospitaldepartment()
    {
        return $this->belongsTo('HospitalDepartment', 'department_id', 'id')->joinType('LEFT');
    }

    public function address()
    {
        return $this->belongsTo('Address', 'address_id', 'id')->joinType('LEFT');
    }

    public function department()
    {
        return $this->belongsTo('DepartmentBasic', 'department_id', 'id')->joinType('LEFT');
    }

    public function document()
    {
        return $this->belongsTo('DocumentType', 'document_type', 'id')->joinType('LEFT');
    }






    /*public function applyReason()
    {
        return $this->belongsTo('MedicalRecordApplyReason', 'apply_reason', 'id')->joinType('LEFT');
    }*/
    /**
     * 获取报价
     */
    public function DayAndNightHours($start_date,$end_date){
        $start_time=strtotime($start_date);
        $next_day=$start_time+86400;
        $first_day_end=strtotime(date('Y-m-d',$next_day).' 00:00:00');

        $end_time=strtotime($end_date);
        $last_day_begin=strtotime(date('Y-m-d',$end_time).' 00:00:00');

        $day_hours=0;
        $night_hours=0;
        if($first_day_end<=$last_day_begin+86400){
            $stage1=ceil(bcdiv($first_day_end-$start_time,3600,2));
            $stage2=ceil(bcdiv($first_day_end-$end_time,3600,2));

            /*if($stage1>4){
                if($stage1>16)
                    $night_hours+=$stage1-16;

                $day_hours+=$stage1-4;
                $night_hours+=4;
            }
            else{
                $night_hours+=$stage1;
            }

            $days=round(($last_day_begin-$first_day_end)/86400);
            $day_hours+=$days*12;
            $night_hours+=$days*12;

            if($stage2>8){
                if($stage2>16)
                    $night_hours+=$stage2-16;

                $day_hours+=$stage2-8;
                $night_hours+=8;
            }
            else{
                $night_hours+=$stage2;
            }*/

            if($stage1>16){
                if($stage2>16)
                    $night_hours+=ceil(bcdiv($end_time-$start_time,3600,2));
                elseif($stage2>4){
                    $night_hours+=$stage1-16;
                    $day_hours+=16-$stage2;
                }
                else{
                    $night_hours+=$stage2-$stage1;
                    $day_hours+=12;
                    $night_hours+=4-$stage2;
                }
            }

            elseif($stage1>4){
                if($stage2>4)
                    $day_hours+=ceil(bcdiv($end_time-$start_time,3600,2));
                else{
                    $day_hours+=$stage1-4;
                    $night_hours+=4-$stage2;
                }
            }
            else
                $night_hours+=ceil(bcdiv($end_time-$start_time,3600,2));

        }
        else{
            $time8=strtotime(date('Y-m-d',$start_time).' 08:00:00');
            $time20=strtotime(date('Y-m-d',$start_time).' 20:00:00');

            if($start_time<$time8){
                if($end_time<$time8)
                    $night_hours+=ceil(($end_time-$start_time)/3600);
                else
                    $night_hours+=ceil(($time8-$start_time)/3600);

                if ($end_time>=$time8&&$end_time<$time20)
                    $day_hours+=ceil(($end_time-$time8)/3600);

                if($end_time>$time20){
                    $night_hours+=ceil(($end_time-$time20)/3600);
                }
            }

            if($start_time>=$time8&&$start_time<$time20){var_dump(2);
                if($end_time<$time20)
                    $day_hours+=ceil(($end_time-$start_time)/3600);
                else
                    $day_hours+=ceil(($time20-$start_time)/3600);

                if($end_time>$time20)
                    $night_hours+=ceil(($end_time-$time20)/3600);
            }

            if($start_time>=$time20) {
                $night_hours += ceil(($end_time - $start_time) / 3600);
            }
        }

        return [$day_hours,$night_hours];
    }

    /**
     * 检查用户是否可以接单
     */
    public function checkWorker($user,$order){
        if($user['working_status']!=1)
            return '非上班状态，不可接单';

        $basic_service=ServiceBasic::get(['code'=>$order['code']])?:[];
        if(!$basic_service)
            return '订单信息错误';

        if(in_array($basic_service['code'],['escort','escort_vip','escort_halfday','escort_overtime','register','inquiry','document','medicine','records'])&&$user['pzy_status']!='normal')
            return "此订单为{$basic_service['name']}类型，非陪诊员不可接此类型订单";

        if(in_array($basic_service['code'],['ward','special_ward','surgery_ward'])&&$user['phy_status']!='normal')
            return "此订单为{$basic_service['name']}类型，非陪护员不可接此类型订单";

        return true;
    }

    /**
     * 6、7订单状态
     */
    public static function fetchCompleteStatus(&$order,$is_worker){
        if($order['status']==6){
            if($is_worker){
                $order['order_text']='服务结束';
            }
            else{
                if($order['patient_commented']==1){
                    $order['order_text']='已评价';
                }
                else{
                    $order['order_text']='已完成';
                }
            }
        }
        if($order['status']==7){
            if($is_worker){
                $order['order_text']='已完成';
            }
            else{
                if($order['patient_commented']==1){
                    $order['order_text']='已评价';
                }
                else{
                    $order['order_text']='已完成';
                }
            }
        }
    }

}
